package tzjz.example.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mikuac.shiro.common.utils.MsgUtils;
import com.mikuac.shiro.core.Bot;
import com.mikuac.shiro.core.BotContainer;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import tzjz.example.entity.GroupQu;
import tzjz.example.entity.Param;
import tzjz.example.entity.SaoHua;
import tzjz.example.service.IGroupQuService;
import tzjz.example.service.IParmSerice;
import tzjz.example.service.ISaoHuaSerice;
import tzjz.example.util.HttpUtil;

import java.io.IOException;
import java.util.List;

/**
 * @author ForteScarlet
 */
@Component
public class MessageSendTask {

    @Resource
    private BotContainer botContainer;
    @Autowired
    private IParmSerice iParmSerice;
    @Autowired
    private ISaoHuaSerice iSaoHuaSerice;

    @Autowired
    private IGroupQuService iGroupQuService;

    /**
     * 早报定时任务
     */
    @Scheduled(cron = "0 0 9 * * ?")
    public void task2() throws IOException {
        // 机器人账号
        long botId = 1701158652L;
        // 通过机器人账号取出 Bot 对象
        Bot bot = botContainer.robots.get(botId);

        Param zaobao = getUrl("zaobao");
        Param moyu = getUrl("moyu");
        Param zaobaotoken = getUrl("zaobaotoken");

        String saoHua = getSaoHua();
        List<GroupQu> groupQus = getAllGroup();

        String s = HttpUtil.get(zaobao.getValue() + "?token=" + zaobaotoken.getValue() + "&format=json");
        final JSONObject json = JSONObject.parseObject(s);
        String data = json.getString("data");
        if (!ObjectUtils.isEmpty(data)) {
            final JSONObject json1 = JSONObject.parseObject(data);
            String url = json1.getString("image");

            String msg = MsgUtils.builder()
                    .img(url)  // 包含一张图片
                    .img(moyu.getValue())  // 包含一张图片
                    .text(saoHua)                 // 包含一段文本内容
                    .build();                       // 构建消息

            for (GroupQu groupQu : groupQus) {
                // 调用 Bot 对象方法
                bot.sendGroupMsg(Long.parseLong(groupQu.getGroupId()), msg, false);
            }
        }
    }

    private List<GroupQu> getAllGroup() {
        QueryWrapper<GroupQu> wrapper = new QueryWrapper<>();
        wrapper.eq("zaobao", "1");
        List<GroupQu> list = iGroupQuService.list(wrapper);
        return list;
    }

    private String getSaoHua() {
        SaoHua saoHua = iSaoHuaSerice.selectByRandom();
        return saoHua.getText();
    }

    private Param getUrl(String url) {
        QueryWrapper<Param> wrapper = new QueryWrapper<>();
        wrapper.eq("param", url);
        Param param = iParmSerice.getOne(wrapper);
        return param;
    }
}

